<template>
    <div class="forget">
        <upNavbar :title="forgetParam" :bgColor="'#fff'"></upNavbar>
        <view class="back">
            <view class="logo">
                <image src="@/static/images/logo.png" alt="" />
                <view class="title">{{ $t('authentication') }}</view>
            </view>
            <!-- 切换邮箱或手机登录 -->
            <!-- <div class="up">
                <up-subsection activeColor="#000" inactiveColor="#fff" bgColor="#DE868F" :list="subsectionList"
                    :current="subsectionCurrent" @change="sectionChange">
                </up-subsection>
            </div> -->
            <div class="phoneFrom">
                <!-- <up-form labelPosition="left" :model="model1" :rules="rules" ref="form1">
                    <up-form-item v-if="subsectionCurrent === 0" class="phoneNumber1" label="" prop="userInfo.number"
                        borderBottom ref="item1">
                        <u-input type="number" v-model="model1.userInfo.number" :placeholder="$t('Pleaseenternumber')"
                            style="flex: 1;"></u-input>
                    </up-form-item>
                    <up-form-item v-else class="phoneNumber1" label="" prop="userInfo.email" borderBottom ref="item1">
                        <u-input type="text" v-model="model1.userInfo.email" :placeholder="$t('Pleaseenteremail')"
                            style="flex: 1;"></u-input>
                    </up-form-item>
                    <up-form-item class="sendCode1" label="" prop="userInfo.sendCode" borderBottom ref="item1">
                        <u-input v-model="model1.userInfo.sendCode" :placeholder="$t('inputCaptcha')" style="flex: 1;"></u-input>
                        <u-button style="width: 160rpx;" :disabled="isDisabled" @click="handSendCode">{{
                            buttonText }}</u-button>
                    </up-form-item>
                </up-form> -->
                <up-form labelPosition="left" :model="model1" :rules="rules" ref="form1">
                    <up-form-item v-if="subsectionCurrent === 0" class="phoneNumber1" label="" prop="userInfo.number"
                        borderBottom ref="item1">
                        <u-input type="number" v-model="model1.userInfo.number" :placeholder="$t('Pleaseenternumber')"
                            style="flex: 1;"></u-input>
                    </up-form-item>
                    <up-form-item v-else class="phoneNumber1" label="" prop="userInfo.email" borderBottom ref="item1">
                        <u-input type="text" v-model="model1.userInfo.email" :placeholder="$t('Pleaseenteremail')"
                            style="flex: 1;"></u-input>
                    </up-form-item>
                    <up-form-item class="sendCode1" label="" prop="userInfo.sendCode" borderBottom ref="item1">
                        <u-input v-model="model1.userInfo.sendCode" :focus="isFocus" :placeholder="$t('inputCaptcha')"
                            style="flex: 1;" @blur="isBlur"></u-input>
                        <u-button style="width: 6rem;" :disabled="isDisabled" @click="handSendCode"
                            :loading="SendCodeLoading" :loadingText="''">{{
                                buttonText }}</u-button>
                    </up-form-item>
                </up-form>
                <div class="logBtn">
                    <u-button type="" :text="$t('nextstep')" @click="nextStep"></u-button>
                </div>
            </div>
        </view>
        <upModal :modalWidth="'14.75rem'" :modalShow="modalShow" :modalTitle="modalTitle" :modalText1="modalText1"
            :showImage="showImage" :isCancel="isCancel" @cloos="cloos">
        </upModal>
        <up-toast ref="uToastRef"></up-toast>
    </div>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive } from 'vue'
import { getPhoneCode, getEmailCode, verifymsgcode } from '@/api/login'
import upNavbar from '../../components/upNavbar.vue';
import upModal from '@/components/upModal.vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const uToastRef = ref(null)
const subsectionList = ref([t('mobilephone'), t('email')])
const subsectionCurrent = ref(0)
const SendCodeLoading = ref(false)
let isFocus = ref(false)// 验证码输入框获取焦点
const isBlur = () => {// 验证码输入框失去焦点
    isFocus.value = false
}
const model1 = reactive({
    userInfo: {
        number: '',
        sendCode: '',
    },
    codeInfo: {
        number: '',
        possWord: '',
    },
})
const rules = {
    'userInfo.number': [
        {
            required: true,
            message: t('Mobilephonenumbercannotempty'),
            trigger: ['blur',]
        },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: t('Themobilephonenumberincorrect'),
            trigger: ['blur',]
        }
    ],
    'userInfo.email': [
        {
            required: true,
            message: t('Mailboxcannotbeempty'),
            trigger: ['blur',]
        },
        {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: t('Incorrectmailboxformat'),
            trigger: ['blur',]
        }
    ],
    'userInfo.sendCode': {
        type: 'string',
        required: true,
        message: t('inputCaptcha'),
        trigger: ['blur',]
    },
}
const isDisabled = ref(false)
const buttonText = ref(t('SendCaptcha'))
const forgetParam = ref('');
const countdown = ref(0);
const form1 = ref(null);

// 弹窗-头
const modalShow = ref(false) // 弹窗显示状态
const showImage = ref(true) // 是否显示图片
const isCancel = ref(false) // 是否有取消按钮
const modalTitle = ref('') // 弹窗标题
const modalText1 = ref('') // 弹窗内容
const cloos = () => {
    modalShow.value = false
}
// 弹窗-尾

const nextStep = () => {// 下一步
    form1.value.validate().then((valid: any) => {
        if (valid) {
            let para = {}
            if (subsectionCurrent.value === 0) {
                para = {
                    emailOrPhone: model1.userInfo.number,
                    msg: model1.userInfo.sendCode,
                }
            } else {
                para = {
                    emailOrPhone: model1.userInfo.email,
                    msg: model1.userInfo.sendCode,
                }
            }
            verifymsgcode(para).then((res: any) => {
                if (res.code == 200) {
                    uni.navigateTo({
                        url: `/pages/login/resetPassword?number=${para.emailOrPhone}&token=${res.data.token}`
                    })
                } else if (res.code == 11116) {// 验证码已过期
                    modalShow.value = true
                    showImage.value = true
                    isCancel.value = false
                    modalText1.value = res.msg
                } else if (res.code == 10102003) {// 输入验证码错误
                    modalShow.value = true
                    showImage.value = true
                    isCancel.value = false
                    modalText1.value = res.msg
                } else {
                    uToastRef.value.show({
                        message: `${res.msg}`,
                        duration: 2000,
                        type: "default",
                        icon: "none",
                    })
                }
            })
        } else { }
    })
}
// 获取验证码
const handSendCode = () => {
    if (isDisabled.value) return;
    let para = {
        phone: model1.userInfo.number
    }
    isFocus.value = true
    if (subsectionCurrent.value === 0) {
        para.phone = model1.userInfo.number
        const phoneReg = /^1[3-9]\d{9}$/
        if (!model1.userInfo.number) {
            uToastRef.value.show({
                message: t('Pleaseenternumber'),
                duration: 2000,
                type: "default",
                icon: "none",
            })
            return
        }
        if (!phoneReg.test(model1.userInfo.number)) {
            uToastRef.value.show({
                message: t('Pleaseentercorrectemailnumber'),
                duration: 2000,
                type: "default",
                icon: "none",
            })
            return
        }
        SendCodeLoading.value = true
        getPhoneCode({ phone: model1.userInfo.number }).then(res => {
            if (res.code === 200) {
                isDisabled.value = true;
                buttonText.value = '60s';
                countdown.value = 60;
                // const intervalId = setInterval(() => {
                //     if (countdown.value <= 0) {
                //         clearInterval(intervalId); // 清除定时器
                //         isDisabled.value = false;
                //         buttonText.value = t('SendCaptcha');
                //     } else {
                //         countdown.value -= 1;
                //         buttonText.value = `${countdown.value}s`;
                //     }
                // }, 1000);
                uToastRef.value.show({
                    message: t('haveSendCode'),
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
            } else {
                uToastRef.value.show({
                    message: `${res.msg}`,
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
            }
        }).catch(err => {
            uToastRef.value.show({
                message: `${err.msg}`,
                duration: 2000,
                type: "default",
                icon: "none",
            })
        }).finally(() => {
            SendCodeLoading.value = false
            const intervalId = setInterval(() => {
                if (countdown.value <= 0) {
                    clearInterval(intervalId); // 清除定时器
                    isDisabled.value = false;
                    buttonText.value = t('SendCaptcha');
                } else {
                    countdown.value -= 1;
                    buttonText.value = `${countdown.value}s`;
                }
            }, 1000);
        })
    } else if (subsectionCurrent.value === 1) {
        para.phone = model1.userInfo.email
        const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
        if (!model1.userInfo.email) {
            uToastRef.value.show({
                message: t('bindEmailPlaseholder'),
                duration: 2000,
                type: "default",
                icon: "none",
            })
            return
        }
        if (!emailReg.test(model1.userInfo.email)) {
            uToastRef.value.show({
                message: t('Pleaseentercorrectemailaddress'),
                duration: 2000,
                type: "default",
                icon: "none",
            })
            return;
        }
        SendCodeLoading.value = true
        getEmailCode(model1.userInfo.email).then(res => {
            if (res.code === 200) {
                isDisabled.value = true;
                buttonText.value = '60s';
                countdown.value = 60;
                uToastRef.value.show({
                    message: t('haveSendCode'),
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
                // const intervalId = setInterval(() => {
                //     if (countdown.value <= 0) {
                //         clearInterval(intervalId); // 清除定时器
                //         isDisabled.value = false;
                //         buttonText.value = t('SendCaptcha');
                //     } else {
                //         countdown.value -= 1;
                //         buttonText.value = `${countdown.value}s`;
                //     }
                // }, 1000);
            } else {
                uToastRef.value.show({
                    message: `${res.msg}`,
                    duration: 2000,
                    type: "default",
                    icon: "none",
                })
            }
        }).catch((err: any) => {
            uToastRef.value.show({
                message: `${err.msg}`,
                duration: 2000,
                type: "default",
                icon: "none",
            })
        }).finally(() => {
            SendCodeLoading.value = false
            const intervalId = setInterval(() => {
                if (countdown.value <= 0) {
                    clearInterval(intervalId); // 清除定时器
                    isDisabled.value = false;
                    buttonText.value = t('SendCaptcha');
                } else {
                    countdown.value -= 1;
                    buttonText.value = `${countdown.value}s`;
                }
            }, 1000);
        })
    }
}
onLoad((options) => {
    // 从 options 中获取参数
    forgetParam.value = options.forget;
});
const sectionChange = (index: number) => {
    subsectionCurrent.value = index;
    // if (index === 0) {
    //     model1.userInfo.email = ''
    // } else {
    //     model1.userInfo.number = ''
    // }
}
</script>
<style scoped lang="scss">
.forget {
    width: 100%;
    height: 100%;
    background: linear-gradient(180deg, #F4E6E6, #ffffff);

    .back {
        width: 100%;
        position: fixed;
        top: 280rpx;

        .logo {
            text-align: center;
            margin-bottom: 30rpx;

            image {
                width: 240rpx;
                height: 240rpx;
            }

            .title {
                font-weight: bold;
            }
        }

        .up {
            width: 50%;
            margin: 0 auto;
        }

        .phoneFrom {
            width: 85%;
            margin: 0 auto;

            .phoneNumber1 {
                .u-input {
                    background-color: #F2F2F2;
                }

                .u-input--radius {
                    border-radius: 15px;
                }
            }

            .sendCode1 {
                .u-input {
                    background-color: #F2F2F2;
                }

                .u-input--radius {
                    border-radius: 15px 0 0 15px;
                }

                .u-button {
                    border-radius: 0 15px 15px 0;
                }
            }

            .logBtn {
                margin: 0 auto;
                margin-top: 28rpx;
                width: 100%;
                text-align: center;

                .u-button {
                    color: #fff;
                    height: 80rpx;
                    font-weight: 600;
                    border-radius: 10px;
                    background-color: #de868f;
                    border: 1px solid #bbbbbb;
                }

            }
        }
    }
}
</style>